package com.ruoyi.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.domain.AutoVueConfig;
import com.ruoyi.mapper.AutoVueConfigMapper;
import com.ruoyi.service.AutoVueConfigService;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * lhp
 * 2024/8/29
 */
@Service
public class AutoVueConfigServiceImpl extends ServiceImpl<AutoVueConfigMapper, AutoVueConfig> implements AutoVueConfigService {
    @Override
    public List<AutoVueConfig> getlist(AutoVueConfig autoVueConfig) {
        List<AutoVueConfig> list = this.query().list();
        return list;
    }

    @Override
    public AjaxResult add(AutoVueConfig autoVueConfig) {
        if(ObjectUtil.isEmpty(autoVueConfig.getId())){
            autoVueConfig.setId(IdUtil.getSnowflakeNextIdStr());
        }
        this.saveOrUpdate(autoVueConfig);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteDate(AutoVueConfig autoVueConfig) {
        if(ObjectUtil.isEmpty(autoVueConfig.getId())){
            return AjaxResult.error("数据为空");
        }
        this.removeById(autoVueConfig.getId());
        return AjaxResult.success("删除成功");
    }

    @Override
    public AjaxResult tobuild(AutoVueConfig autoVueConfig) {
        if(ObjectUtil.isEmpty(autoVueConfig.getId())){
            return AjaxResult.error("数据为空");
        }
        AutoVueConfig byId = this.getById(autoVueConfig.getId());
        String projectPath = byId.getVuePath(); // 替换为你的Vue项目路径
        String npmPath = byId.getNodePath()+"\\npm.cmd"; // 替换为实际路径
        try {
            // 运行Vue CLI的构建命令
            ProcessBuilder vueBuildBuilder = new ProcessBuilder(npmPath, "run", "build:prod");
            vueBuildBuilder.directory(new java.io.File(projectPath));
            Process vueBuildProcess = vueBuildBuilder.start();

            // 读取构建过程的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(vueBuildProcess.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = vueBuildProcess.waitFor();
            System.out.println("Process exited with code: " + exitCode);

            if (exitCode == 0) {
                return AjaxResult.success("构建成功");
            } else {
                return AjaxResult.success("构建失败");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

}
